<?php

namespace frontend\modules\Api\controllers;

use common\models\TallyAccount;
use common\models\TallyRecord;
use common\services\TallyAccountService;
use common\services\TallyCategoryService;
use common\services\TallyMemberService;
use common\services\TallyProjectService;
use common\services\TallyRecordService;
use common\services\TallyStockRecordService;
use common\services\ToolService;
use frontend\modules\Dao\TallyRecordDao;
use Yii;
use yii\base\ExitException;
use yii\filters\AccessControl;
use yii\helpers\ArrayHelper;

class RecordAnalysisController extends ApiController
{



    /**
     * @return array
     * 引入行为验证 过滤授权
     */
    public function behaviors()
    {
        $config = [
            'access' => [
                'class' => AccessControl::className(),
                'denyCallback' => function($rule, $action){
                    return self::failureResponse(100001, '请先登录!',[]);
                },
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'],
                    ]
                ]
            ],
        ];
        return ArrayHelper::merge(parent::behaviors(), $config);
    }



    public function actionSummaryDebt(){
        if(Yii::$app->request->isPost){

            $tallyId = Yii::$app->getRequest()->post('tally_id');

        }else{

            $tallyId = Yii::$app->getRequest()->get('tally_id');

        }
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        // 检查账本权限 是否可读
        $this->checkRolePermission($this->_user['id'],$tallyId,'read');
        $asset = TallyAccountService::sumAll([
            //['=','uid',$this->_user['id']],
            ['>','money',0],
            ['=','tally_id', $tallyId]
        ]);
        $asset = ToolService::moneyFormat($asset); // 总资产
        $debt  = TallyAccountService::sumAll([
            //['=','uid',$this->_user['id']],
            ['<','money',0],
            ['=','tally_id', $tallyId]
        ]);
        $debt = ToolService::moneyFormat(abs($debt)); // 总负债
        $smInfo = [
            'asset_net'=> ToolService::moneyFormat($asset -  $debt) , //净资产
            'asset' => $asset , //资产
            'debt' => $debt , //负债
        ] ;
        $smInfo['caiin'] = TallyStockRecordService::getQuery($tallyId,[
            'sales_type'=>30,
            'state'=>1
        ])->sum('tally_money') ?? 0;

        $smInfo['caiin_format'] = ToolService::moneyType($smInfo['caiin']);
        return self::successResponse($smInfo);
    }



    public function actionAccountDatasLists(){
        if(Yii::$app->request->isPost){
            $tallyId = Yii::$app->getRequest()->post('tally_id');
        }else{
            $tallyId = Yii::$app->getRequest()->get('tally_id');
        }
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        $zichans = ['现金账户','金融账户','虚拟账户','信用账户','投资账户','其他账户'];
        $fuzhais = ['负债账户','债权账户'];
        $arr_tip_str_arr = [
            '现金账户'=>0,
            '金融账户'=>1,
            '虚拟账户'=>2,
            '信用账户'=>3,
            '负债账户'=>4,
            '债权账户'=>5,
            '投资账户'=>6,
            '其他账户'=>7,
            '未知账户'=>8,
        ];
        $all_group = json_decode(ToolService::getConfig('DEFAULT_ACCOUNT_TAG'),true);
        $zichan_accounts = TallyAccount::find()->where([
            'tally_id'=>$tallyId
        ])->andFilterWhere(['in','tag',$zichans])->asArray()->all();
        foreach ($zichan_accounts as &$value){
            $value['img_url'] = $all_group[$arr_tip_str_arr[$value['tag']]]['img_url'];
        }
        $fuzhai_accounts = TallyAccount::find()->where([
            'tally_id'=>$tallyId
        ])->andFilterWhere(['in','tag',$fuzhais])->asArray()->all();
        foreach ($fuzhai_accounts as &$value){
            $value['img_url'] = $all_group[$arr_tip_str_arr[$value['tag']]]['img_url'];
        }
        return self::successResponse([
            'zichans'=>$zichan_accounts,
            'fuzhai'=>$fuzhai_accounts
        ]);

    }



    /**
     * @throws ExitException
     */
    public function actionCountDebts(){
        $condition = Yii::$app->request->get(); // type 等参数
        $tallyId = Yii::$app->getRequest()->get('tally_id');
        if(!$tallyId){
            return self::failureResponse(500,'账本id不能为空');
        }
        $this->checkRolePermission($this->_user['id'],$tallyId);
        $retData  = TallyRecordService::countDebt($condition);
        $retData['in_format']  = ToolService::moneyType($retData['in']);
        $retData['out_format']  = ToolService::moneyType($retData['out']);
        $retData['debt_format']  = ToolService::moneyType($retData['debt']);
        //查询采购单
        $retData['caiin'] = TallyStockRecordService::getQuery($tallyId,[
            'sales_type'=>30,
            'state'=>1
        ])->sum('tally_money');

        $retData['caiin_format'] = ToolService::moneyType($retData['caiin']);
        return self::successResponse($retData);
    }




    public function actionMemberDataV(){
        $tallyId = Yii::$app->getRequest()->get('tally_id',58);
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        //表格数据收入
        $tally_recordss = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId
        ])->andFilterWhere(['<>','member_id',0])
            ->groupBy('member_id')
            ->select('member_id,count(*) as counts')
            ->asArray()
            ->all();
    }


    public function actionMemberData(){
        $tallyId = Yii::$app->getRequest()->get('tally_id',58);
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }
        //表格数据
        $tally_recordss = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId,
            'type'=>10
        ])->andFilterWhere(['<>','member_id',0])
        ->groupBy('member_id')
        ->select('member_id,sum(amount) as counts')
        ->orderBy('counts desc')
        ->asArray()
        ->limit(5)
        ->all();
        $shourusMembers = 0;
        $zhichuMembers = 0;
        if(!empty($tally_recordss)){
            $shourusMembers = TallyRecordDao::get_builder([
                'tally_id'=>$tallyId,
                'state'=>1,
                'type'=>10
            ])->andFilterWhere(['in','member_id',array_column($tally_recordss,'member_id')])->sum('amount');
            $zhichuMembers = TallyRecordDao::get_builder([
                'tally_id'=>$tallyId,
                'state'=>1,
                'type'=>20
            ])->andFilterWhere(['in','member_id',array_column($tally_recordss,'member_id')])->sum('amount');
        }

        foreach ($tally_recordss as &$value){

            $value['member_name'] = TallyMemberService::getTitleById($value['member_id']);
            //获取收入
            $value['shouru_money'] = TallyRecordDao::get_builder([
                'tally_id'=>$tallyId,
                'member_id'=>$value['member_id'],
                'state'=>1,
                'type'=>10
            ])->sum('amount') ?? 0;
            $value['shouru_money_format'] = ToolService::moneyType($value['shouru_money']);
            $value['zhichu_money'] = TallyRecordDao::get_builder([
                'tally_id'=>$tallyId,
                'member_id'=>$value['member_id'],
                'state'=>1,
                'type'=>20
            ])->sum('amount') ?? 0;




            $value['zhichu_money_format'] = ToolService::moneyType($value['zhichu_money']);
            $value['lirun'] = bcsub($value['shouru_money'],$value['zhichu_money'],2);
            $value['lirun_format'] = ToolService::moneyType($value['lirun']);
            $value['shouru_rate'] = round($value['shouru_money'] / $shourusMembers,2);
            $value['zhichu_rate'] = round($value['zhichu_money'] / $zhichuMembers,2);

        }
        return self::successResponse($tally_recordss);
    }





        public function actionXiangMuData(){
            $tallyId = Yii::$app->getRequest()->get('tally_id',58);
            if(!$tallyId){
                return self::failureResponse(500,'账本Id不能为空');
            }
            //表格数据
            $tally_recordss = TallyRecordDao::get_builder([
                'tally_id'=>$tallyId
            ])->andFilterWhere(['<>','project_id',0])
                ->groupBy('project_id')
                ->select('project_id,,sum(amount) as counts')
                ->orderBy('counts desc')
                ->limit(5)
                ->asArray()
                ->all();
            $shourusMembers = 0;
            $zhichuMembers = 0;
            if(!empty($tally_recordss)){
                $shourusMembers = TallyRecordDao::get_builder([
                    'tally_id'=>$tallyId,
                    'state'=>1,
                    'type'=>10
                ])->andFilterWhere(['in','project_id',array_column($tally_recordss,'project_id')])->sum('amount');
                $zhichuMembers = TallyRecordDao::get_builder([
                    'tally_id'=>$tallyId,
                    'state'=>1,
                    'type'=>20
                ])->andFilterWhere(['in','project_id',array_column($tally_recordss,'project_id')])->sum('amount');


            }

            foreach ($tally_recordss as &$value){
                $value['project_name'] = TallyProjectService::getTitleById($value['project_id']);
                //获取收入
                $value['shouru_money'] = TallyRecordDao::get_builder([
                    'tally_id'=>$tallyId,
                    'project_id'=>$value['project_id'],
                    'state'=>1,
                    'type'=>10
                ])->sum('amount') ?? 0;
                $value['shouru_money_format'] = ToolService::moneyType($value['shouru_money']);
                $value['zhichu_money'] = TallyRecordDao::get_builder([
                    'tally_id'=>$tallyId,
                    'project_id'=>$value['project_id'],
                    'state'=>1,
                    'type'=>20
                ])->sum('amount') ?? 0;
                $value['zhichu_money_format'] = ToolService::moneyType($value['zhichu_money']);
                $value['lirun'] = bcsub($value['shouru_money'],$value['zhichu_money'],2);
                $value['lirun_format'] = ToolService::moneyType($value['lirun']);
                $value['shouru_rate'] = round($value['shouru_money'] / $shourusMembers,2);
                $value['zhichu_rate'] = round($value['zhichu_money'] / $zhichuMembers,2);
            }
            return self::successResponse($tally_recordss);
        }




    public function actionMonthShouZhiRecord()
    {
        $month_arr = [];
        $tallyId = Yii::$app->getRequest()->get('tally_id',58);
        if(!$tallyId){
            return self::failureResponse(500,'账本Id不能为空');
        }


        $params = Yii::$app->getRequest()->get();

        $be_data = [];
        //月份
        if($this->checkIsHasField($params,'month_type')){
            if($params['month_type'] == 2){
                for ($i=1;$i<13;$i++){
                    $month_str =  $i.'月';

                    if($i < 10){
                        $i  = '0'.$i;
                    }
                    $start_date = date('Y').'-'.$i.'-01';
                    $end_date = date('Y-m-d', mktime(23, 59, 59, date('m', strtotime($start_date))+1, 00)).' 23:59:59';
                    $be_data[] = [
                        'start_date'=>$start_date,
                        'end_date'=>$end_date,
                        'str' => $month_str
                    ];
                }
            }else if($params['month_type'] == 0){
                $month = date('Y-m');
                $year_start = date("Y-m-01",strtotime($month));
                $year_end = date("Y-m",strtotime($month)).'-'.date('t',strtotime($month));
                $start_day = strtotime($year_start);
                // 如果当月第一天是不是周一获取下一个周一的时间戳
                $year_mon_dy = date("Y-m-d", $start_day);
                $end_day = strtotime($year_end);
                // 如果当月最后一天不是周日获取下一个周日的时间戳
                $year_sun_dy = date('Y-m-d',$end_day);
                $day_diff = ceil((((strtotime($year_sun_dy) - strtotime($year_mon_dy))/86400) + 1) / 6);
                $start_ymd = [];
                for ($i=0;$i<$day_diff;$i++){
                    $value = date('Y-m-d',strtotime($year_mon_dy) + $i * 86400 * 6 );
                    $start_ymd[$i+1] = $value;
                }
                $start_ymd[count($start_ymd)] = date('Y-m-t');
                for($key=1;$key<count($start_ymd);$key++){
                    $be_data[] = [
                        'start_date'=>$start_ymd[$key],
                        'end_date'=>$start_ymd[$key+1].' 23:59:59',
                        'str'=>'第'.$key.'周'
                    ];
                }

            }else if($params['month_type'] == 1){
                $month = date('m');
                $yue_arr = [0,1,1,1,4,4,4,7,7,7,10,10,10];
                $yue_date_end = [31,28,31,30,31,30,31,30,31,30,31,30,31];
                $ztart_yue = $yue_arr[$month];
                for ($i=0;$i<3;$i++){
                    $value_yue = $ztart_yue;
                    if($ztart_yue < 10){
                        $ztart_yue = '0'.$ztart_yue;
                    }
                    $be_data[] = [
                        'start_date'=>date('Y-').$ztart_yue.'-01',
                        'end_date'=>date('Y-').$ztart_yue.'-'.$yue_date_end[$value_yue].' 23:59:59',
                        'str'=>$value_yue.'月'
                    ];
                    $ztart_yue = $value_yue+1;
                }
            }
        }

        foreach ($be_data as &$item){
            $item['shouru_moneys'] = TallyRecord::find()
                ->where([
                    'type'=>10,
                    'state'=>1,
                    'tally_id'=>$tallyId,
                ])
                ->andFilterWhere(['>=','tally_time',$item['start_date']])
                ->andFilterWhere(['<=','tally_time',$item['end_date']])
                ->sum('amount') ?? 0.00;

            $item['zhichu_moneys'] = TallyRecord::find()
                ->where([
                    'type'=>20,
                    'state'=>1,
                    'tally_id'=>$tallyId
                ])
                ->andFilterWhere(['>=','tally_time',$item['start_date']])
                ->andFilterWhere(['<=','tally_time',$item['end_date']])
                ->sum('amount') ?? 0.00;
            $item['debt'] = bcsub($item['shouru_moneys'],$item['zhichu_moneys'],2);
            $month_arr[] = $item;
        }



        $start_date = $be_data[0]['start_date'];
        $end_date = $be_data[count($be_data)-1]['end_date'];


        //获取收入分类排名前6
        $category_shourus = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId,
            'type'=>10,
            'state'=>1
        ])->andFilterWhere(['>','tally_time',$start_date])
            ->andFilterWhere(['<=','tally_time',$end_date])->select(['category_id','sum(amount) as prices'])
            ->groupBy(['category_id'])->andFilterWhere([
                '<>','category_id',0
            ])->orderBy('prices desc')->limit(6)->asArray()->all();
        $moneys_shouru = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId,
            'type'=>10,
            'state'=>1
        ])->andFilterWhere(['>','tally_time',$start_date])
            ->andFilterWhere(['<=','tally_time',$end_date])->sum('amount');
        foreach ($category_shourus as &$value){
            $value['category_name'] = TallyCategoryService::getCateInfoById($value['category_id'])['title'] ?? '暂无分类名称';
            $value['category_pi'] = bcdiv($value['prices'],$moneys_shouru,2);
            if($value['category_pi'] < 0.01){
                $value['category_pi'] = 0.01;
            }
        }


        $category_zhichus = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId,
            'type'=>20,
            'state'=>1
        ])->andFilterWhere(['>','tally_time',$start_date])
            ->andFilterWhere(['<=','tally_time',$end_date])
            ->select(['category_id','sum(amount) as prices'])
            ->groupBy(['category_id'])
            ->andFilterWhere([
                '<>','category_id',0
            ])->orderBy('prices desc')->limit(6)->asArray()->all();

        $moneys_zhichu = TallyRecordDao::get_builder([
            'tally_id'=>$tallyId,
            'type'=>20,
            'state'=>1
        ])->andFilterWhere(['>','tally_time',$start_date])
            ->andFilterWhere(['<=','tally_time',$end_date])->sum('amount');
        foreach ($category_zhichus as &$value){
            $value['category_name'] = TallyCategoryService::getCateInfoById($value['category_id'])['title'] ?? '暂无分类名称';
            $value['category_pi'] = bcdiv($value['prices'],$moneys_zhichu,2);
            if($value['category_pi'] < 0.01){
                $value['category_pi'] = 0.01;
            }
        }




        return self::successResponse([
            'month_arr_zhexian'=>$month_arr,
            'zhichufenlei'=>$category_zhichus,
            'shourufenlei'=>$category_shourus
        ]);
    }







}